package com.nari.ysphd.ui;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ListView;
import android.widget.Toast;

import com.jeremyfeinstein.gson.OnResponse;
import com.jeremyfeinstein.gson.TenantInfo;
import com.jeremyfeinstein.gson.User;
import com.jeremyfeinstein.gson.bean.LoginBean;
import com.jeremyfeinstein.okhttputil.callback.StringCallback;
import com.jeremyfeinstein.utils.AESUtil;
import com.jeremyfeinstein.utils.AppConstants;
import com.jeremyfeinstein.utils.ConfigUtil;
import com.jeremyfeinstein.utils.NetUtils.ApiResponse;
import com.jeremyfeinstein.utils.NetUtils.JsonCallback;
import com.jeremyfeinstein.utils.NetUtils.SGApiService;
import com.jeremyfeinstein.utils.SPUtil;
import com.jeremyfeinstein.utils.ToastUtil;
import com.jeremyfeinstein.utils.YCHSInstance;
import com.jeremyfeinstein.utils.YCHShttpAPI;
import com.nari.ysphd.MyApp;
import com.nari.ysphd.R;
import com.nari.ysphd.adapter.SelectUserAdapter;
import com.nari.ysphd.util.APPUtils;
import com.nari.ysphd.util.ActivityManager;
import com.nari.ysphd.util.log.HDMsgUtils;
import com.orhanobut.logger.Logger;

import java.util.List;

import nari.mip.core.Platform;
import okhttp3.Call;

public class LoginUI extends BaseActivity /*implements OnClickListener*/ {
    private static final String TAG = LoginUI.class.getSimpleName();
    private ProgressDialog progressDialog;
    private String /*searchName, */tenantUserId;
    private List<TenantInfo> tenantList;
    private SelectUserAdapter selectUserAdapter;
    private AlertDialog.Builder tenantBuilder;
    private View tenantView;
    private LayoutInflater mInflater;
    private OnResponse onResponse;


    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        initViews();
        initTenantView();
        //sendRSAPublicKey();
        loginPlatform();
    }

    private void loginPlatform() {

        byte[] encode = Base64.encode("1qaz2wsx#".getBytes(), Base64.DEFAULT);
        String s = new String(encode);

        String Platform_IP = (String) SPUtil.get(AppConstants.Platform_IP, "");
        String Platform_PORT = (String) SPUtil.get(AppConstants.Platform_PORT, "");

//        String url = "http://" + Platform_IP + ":" + Platform_PORT + "/pi6000-ua-web/api/ua/auth/validateUser";
        String url = "http://172.16.219.211/pi6000-ua-web/api/ua/auth/validateUser";
        SGApiService.postJSON(url)
                .addParam("username", "piadmin")
                .addParam("upwd", s)
                .post(new JsonCallback<LoginBean>() {
                    @Override
                    public void onSuccess(ApiResponse<LoginBean> response) {
                        super.onSuccess(response);
                        Logger.e("Response  %s", "onSuccess: " + response.body);
                        if (response.status == 200) {
                            HDMsgUtils.token = response.body.getData().getToken();
                            sendRSAPublicKey();
                        } else {
                            ToastUtil.showLong(MyApp.getApp(), "调用平台服务失败");
                            finish();
                        }
                    }

                    @Override
                    public void onError(ApiResponse<LoginBean> response) {
                        super.onError(response);
                        Logger.e("Response  %s", "onError: " + response.message);
                        ToastUtil.showLong(MyApp.getApp(), "调用平台服务失败 " + response.message);
                        finish();
                    }
                });
    }

    private void sendRSAPublicKey() {
        YCHShttpAPI.signInSalt(MyApp.getApp(), new StringCallback(false) {
            @Override
            public void onError(Call call, int statusCode, Exception e) {
                Log.e(TAG, "onError: ", e);
                ToastUtil.showLong(MyApp.getApp(), "调用UAP服务失败");
                finish();
            }

            @Override
            public void onResponse(String response) {
                try {
                    AESUtil.setAesK(response);
                    signInForPerformance();
                } catch (Exception e) {
                    Log.e(TAG, "onResponse: ", e);
                }
            }
        });
    }

    private void initTenantView() {
        selectUserAdapter = new SelectUserAdapter(this, R.layout.adapter_item_select_user);
        mInflater = LayoutInflater.from(this);
        tenantView = mInflater.inflate(R.layout.dialog_select_user, null);
    }


    /**
     * 进行确认租户请求
     */
    private void performConfirmTenantRequest(String tenantId) {
        YCHShttpAPI.tenantSignIn(this, tenantId, performSearchCallback);
    }

    StringCallback performSearchCallback = new StringCallback() {
        @Override
        public void onError(Call call, int statusCode, Exception e) {
            progressDialogDismiss();
            Logger.e("performSearchCallback" + e.getMessage());
            ToastUtil.showToast("租户登录请求异常！");
            finish();
        }

        @Override
        public void onResponse(String response) {
            progressDialogDismiss();
            OnResponse tenant = YCHShttpAPI.getOnResponse(response);
            if ("0".equals(tenant.getResultCode())) {
                performLogin(onResponse);
            } else if ("-2".equals(tenant.getResultCode())) {
                Intent intent = new Intent(LoginUI.this, TimeOutActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
            } else {
                ToastUtil.showToast(tenant.getErrorMessage());
                finish();
            }

        }
    };

    private void signInForPerformance() {
        Log.d(TAG, "signInForPerformance: ");
        String name = Platform.getCurrent().getMembership().getCurrentUser().getUserName();

        YCHShttpAPI.SignIn(this, name, APPUtils.getIPAddress(this), new StringCallback() {
            @Override
            public void onError(Call call, int statusCode, Exception e) {
                Log.e(TAG, "SignIn onError: " + e.getMessage());
                ToastUtil.showLong(MyApp.getApp(), "调用UAP服务失败！");
                finish();
            }

            @Override
            public void onResponse(String response) {
                onResponse = YCHShttpAPI.getOnResponse(response);
                if ("0".equals(onResponse.getResultCode())) {
                    ConfigUtil.getInstance().setSessionId(onResponse.getSessionid());
                    tenantList = onResponse.getTenantList();
                    if (tenantList == null || tenantList.size() == 0) {
                        ToastUtil.showLong(LoginUI.this, "租户列表为空！");
                        return;
                    }
                    selectUserAdapter.addItems(tenantList);
                    showTenantListDialog();
                } else if ("-2".equals(onResponse.getResultCode())) {
                    Intent intent = new Intent(LoginUI.this, TimeOutActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                } else {
                    if ("6".equals(onResponse.getResultCode())) {
                        showErrorWithStatus(onResponse.getErrorMessage());
                        return;
                    }
//                    if (AppConstants.TAG_LOGINOUT.equals(onResponse.getErrorMessage())){
//                        ActivityManager.getInstance().finishActivityExcept(IPConfigActivity.class);
//                        Platform.getCurrent().stop(getApplicationContext());
//                        ToastUtil.showLong(MyApp.getApp(),onResponse.getErrorMessage());
//                        return;
//                    }
                    ToastUtil.showLong(MyApp.getApp(), onResponse.getErrorMessage());
                    jumpToMipLogin();

                }

            }
        });
    }

    /**
     * 显示租户列表对话框
     */
    private void showTenantListDialog() {
        tenantBuilder = new AlertDialog.Builder(LoginUI.this);
        tenantBuilder.setTitle("租户信息列表");
        //  tenantBuilder.setView(R.layout.dialog_select_user);
        tenantBuilder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        tenantBuilder.setAdapter(selectUserAdapter, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                ListView dialog_list = (ListView) tenantView.findViewById(R.id.dialog_list);
                dialog_list.setAdapter(selectUserAdapter);
                TenantInfo user = (TenantInfo) selectUserAdapter.getItem(which);
                if (!TextUtils.isEmpty(user.tenantName) && !TextUtils.isEmpty(user.tenantId)) {
                    tenantUserId = user.tenantId;
                }
                progressDialog = ProgressDialog.show(LoginUI.this, null, "正在登录租户...");
                performConfirmTenantRequest(tenantUserId);
            }
        });
        tenantBuilder.create().show();

    }

    private void progressDialogDismiss() {
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
    }

    public void showSuccessWithStatus(String successWithStatus) {
        Toast.makeText(this, successWithStatus, Toast.LENGTH_SHORT).show();
    }

    public void showErrorWithStatus(String errorWithStatus) {
        Toast.makeText(this, errorWithStatus, Toast.LENGTH_SHORT).show();
    }

    private void performLogin(OnResponse onResponse) {
        YCHSInstance.getInstance().setLoginUser(onResponse.getUser());
        User user = onResponse.getUser();
        Log.d("GetTime", user.toString());
        ConfigUtil.getInstance().setLoginUser(user);

        ConfigUtil.getInstance().setMeeting_resource(onResponse.getMeeting_resource());

        String localUrl = AppConstants.PC_WEB_REQUEST_MODE + ConfigUtil.getInstance().getRemoteUrl() + ":" + ConfigUtil.getInstance().getRemotePort();
        ConfigUtil.getInstance().saveLocalSocketUrl(localUrl);
        AppConstants.turnAddrLocal = onResponse.getAgent_server_ip();
        Logger.e("initSocket :" + ConfigUtil.getInstance().getRemoteUrl() + ":" + ConfigUtil.getInstance().getRemotePort());

        ConfigUtil.getInstance().setLocalPort(onResponse.getLocal_port3(), onResponse.getLocal_port4());

        ConfigUtil.getInstance().setAppServerHttpPort(onResponse.getApp_server_port1());
        ConfigUtil.getInstance().setAppServerHttpsPort(onResponse.getApp_server_port5());
        SPUtil.put(AppConstants.SERVER_PORT1, onResponse.getApp_server_port1());
        SPUtil.put(AppConstants.SERVER_PORT5, onResponse.getApp_server_port5());
        try {
            if (onResponse.getAgent_server_ip().equals(ConfigUtil.getInstance().getAgentServer())
                    && onResponse.getServer_port1().equals(ConfigUtil.getInstance().getMCUPort1())
                    && onResponse.getServer_port2().equals(ConfigUtil.getInstance().getMCUPort2())) {
            } else {
                ConfigUtil.getInstance().setServerPort(onResponse.getServer_port1(),
                        onResponse.getServer_port2(), onResponse.getServer_port3(),
                        onResponse.getServer_port4());
                ConfigUtil.getInstance().setAgentServer(onResponse.getAgent_server_ip());
            }
        } catch (Exception e) {
            ToastUtil.showToast(e.getMessage());
        }

        AppConstants.meetingResoure = onResponse.getMeeting_resource(); // 1网省 2总部
        if (!(ConfigUtil.getInstance().getRemoteUrl().equals(onResponse.getAgent_server_ip())
                && ConfigUtil.getInstance().getRemotePort().equals(onResponse.getServer_port2()))) {
            Logger.e("initRemoteSocket :" + onResponse.getAgent_server_ip() + ":" + onResponse.getApp_server_port5());
            String remoteUrl = AppConstants.PC_WEB_REQUEST_MODE + onResponse.getAgent_server_ip() + ":" + onResponse.getApp_server_port5();
            ConfigUtil.getInstance().saveRemoteSocketUrl(remoteUrl);
            AppConstants.turnAddrRemote = onResponse.getAgent_server_ip();
            String port = AppConstants.isHttps ? (String) SPUtil.get(AppConstants.SERVER_PORT5, "") : (String) SPUtil.get(AppConstants.SERVER_PORT1, "");
            Logger.e("二级互动:  " + port);
            String url = AppConstants.PC_WEB_REQUEST_MODE + ConfigUtil.getInstance().getAgentServer() + ":" + port;
            SPUtil.put(AppConstants.REMOTE_SOCKET_URL, url);
            SPUtil.put(AppConstants.HAS_REMOTE_SOCKET, true);
        } else {
            SPUtil.put(AppConstants.HAS_REMOTE_SOCKET, false);
        }
        Logger.e("sessionId :" + onResponse.getSessionid());

        Intent intent = new Intent(LoginUI.this, MeetingListActivity.class);
        startActivity(intent);
        finish();
    }

}
